//
//  HRRegestViewController.m
//  Hear
//
//  Created by mac on 2017/3/28.
//  Copyright © 2017年 mac. All rights reserved.
// 注册

#import "HRRegestViewController.h"
#import "HRRegestRootView.h"
#import "HRFillInformationViewController.h"
#import "HRVerificationCodeModel.h"
#import "HRRegestViewModel.h"
#import "HRVerificationCodeModel.h"
#import "HRForgetPasswordViewModel.h"
#import "HRUpdataUserInfoModel.h"
#import "HRRegisterModel.h"
#import "HREnterInvitationCodeViewController.h"
@interface HRRegestViewController ()
@property (nonatomic, strong)HRRegestRootView *rootView;
@property (nonatomic, strong)HRRegestViewModel *viewModel;
@property (nonatomic, strong)HRForgetPasswordViewModel *forgetPasswordViewModel;
@end

@implementation HRRegestViewController


-(HRForgetPasswordViewModel *)forgetPasswordViewModel
{
    if (_forgetPasswordViewModel == nil)
    {
        _forgetPasswordViewModel = [HRForgetPasswordViewModel new];
    }
    return _forgetPasswordViewModel;
}

-(HRRegestViewModel *)viewModel
{
    if (_viewModel == nil)
    {
        _viewModel = [HRRegestViewModel new];
    }
    return _viewModel;
}

-(HRRegestRootView *)rootView
{
    if (_rootView == nil)
    {
        WeakSelf
        _rootView = [[HRRegestRootView alloc] initWithFrame:CGRectZero andControlType:self.controlType];
        [self.view addSubview:(self.rootView = _rootView)];
        
        [_rootView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.left.top.bottom.mas_equalTo(0);
        }];
        _rootView.getCodeButtonClickBlock = ^(NSString *mobileStr){
            [weakSelf.view endEditing:NO];
            if (weakSelf.controlType == RegisterVC){
                [weakSelf.viewModel checkMobileIsReg:@{@"mobile":mobileStr} andResult:^(NSDictionary *result) {
                    if ([result[@"CodeStatus"] intValue] == 40008){
                        [MBProgressHUD showMessage:@"已注册" finishBlock:nil];

                    }else{
                        HRReuestCodeModel *paramModel = [HRReuestCodeModel new];
                        paramModel.mobile = mobileStr;
                        [weakSelf.viewModel getVerificationCodeParam:paramModel andRegestResult:^(NSDictionary *result) {
                            HRVerificationCodeModel *codeModel = [HRVerificationCodeModel modelWithJSON:result[@"BodyContent"]];
                            weakSelf.rootView.codeModel = codeModel;
                            
                            [weakSelf.rootView startCountWhenClickVerRequest];
                        }];
                    }
                }];
            }else{
                HRReuestCodeModel *paramModel = [HRReuestCodeModel new];
                paramModel.mobile = mobileStr;
                [weakSelf.viewModel getVerificationCodeParam:paramModel andRegestResult:^(NSDictionary *result) {
                    HRVerificationCodeModel *codeModel = [HRVerificationCodeModel modelWithJSON:result[@"BodyContent"]];
                    weakSelf.rootView.codeModel = codeModel;
                    [weakSelf.rootView startCountWhenClickVerRequest];
                    
                }];
            }
            
        };
        _rootView.nextButtonClickBlock = ^(){
            
            [weakSelf clickNext];
        };
    }
    return _rootView;
}

- (void)clickNext
{
    WeakSelf
    if (self.controlType == RegisterVC)
    {
        HRFillInformationViewController *infoVC = [HRFillInformationViewController new];
        infoVC.codeModel = self.rootView.codeModel;
        [self.navigationController pushViewController:infoVC animated:YES];
    }else if (self.controlType == ForgetPasswordVC){
        HRRegisterRequstModel *requstModel = [HRRegisterRequstModel new];
        requstModel.MobileNumber = self.rootView.codeModel.Mobile;
        requstModel.Password = self.rootView.codeModel.password;
        [self.forgetPasswordViewModel forgetPasswordParam:requstModel andSeccess:^(BOOL seccess) {
            if (seccess)
            {
                [weakSelf.navigationController popViewControllerAnimated:YES];
                [MBProgressHUD showMessage:@"修改成功，请登录" finishBlock:nil];
            }else{
                [MBProgressHUD showMessage:@"修改失败，请重试" finishBlock:nil];
            }
        }];
    }else if (self.controlType == BindingMobileNumberVC){
        if (self.isFromRegister){
            [self.viewModel checkMobileIsReg:@{@"mobile":self.rootView.codeModel.Mobile,@"openId":self.respDict[@"openId"],@"loginType":_respDict[@"loginType"]} andResult:^(NSDictionary *result) {
                if ([result[@"CodeStatus"] intValue] == 40008){
                    [weakSelf otherLogin:self.respDict];
                }else if ([result[@"CodeStatus"] intValue] == 40010){
                    HRFillInformationViewController *fillVC = [HRFillInformationViewController new];
                    fillVC.respDict = self.respDict;
                    fillVC.Mobile = self.rootView.codeModel.Mobile;
                    [weakSelf.navigationController pushViewController:fillVC animated:YES];
                    
                }
            }];
        }else{
            HRUpdataUserInfoModel*model = [HRUpdataUserInfoModel modelWithJSON:USERINFO];
            
            NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
            paramDict[@"UserLocalId"] = model.LocalId;
            paramDict[@"MobileNumber"] = self.rootView.codeModel.Mobile;
            paramDict[@"Password"] = model.Password;
            [self.forgetPasswordViewModel putBiningUserInfo:paramDict isSeccess:^(BOOL isSeccess) {
                if (isSeccess){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        HREnterInvitationCodeViewController *codeVC = [HREnterInvitationCodeViewController new];
                        [weakSelf.navigationController pushViewController:codeVC animated:YES];
                    });
                }
            }];
        }
    }
}



#pragma 第三方登录
- (void)otherLogin:(NSDictionary *)resp{
    
    
    WeakSelf
    [self.viewModel checkIsRegisterUser:@{@"openId":resp[@"openId"],@"loginType":resp[@"loginType"]} andResult:^(NSDictionary *result) {
        if (result){
            if ([result[@"CodeStatus"] intValue] == 20000){// 已注册
                DDLog(@"");
                [[NSUserDefaults standardUserDefaults]setObject:result[@"BodyContent"] forKey:@"userInfo"];
                
                HRUpdataUserInfoModel*model = [HRUpdataUserInfoModel modelWithJSON:USERINFO];
                [[NSUserDefaults standardUserDefaults] setObject:model.LocalId forKey:@"userid"];
                [weakSelf otherLoginHear:model];

            }
        }
    }];
    
}

- (void)otherLoginHear:(HRUpdataUserInfoModel *)model{
    [self loginEaseMob];
    
    //    [[MyPlayTool sharePlayTool] stop];
    
    [[NSUserDefaults standardUserDefaults] setObject:model.LocalId forKey:@"userid"];
    [[NSUserDefaults standardUserDefaults] setObject:model.QuestionID forKey:@"QuestionID"];
    [[NSUserDefaults standardUserDefaults] setObject:model.QuestionText forKey:@"QuestionText"];
    [[NSUserDefaults standardUserDefaults] setObject:model.UserCoverPicture forKey:@"UserCoverPicture"];
    [[NSUserDefaults standardUserDefaults] setObject:model.LocalId forKey:@"userid"];
    [[NSUserDefaults standardUserDefaults] setObject:model.UserPictureName forKey:@"iconName"];
    [[NSUserDefaults standardUserDefaults] setObject:model.UserPictureBackgroundColor forKey:@"iconColor"];
    [[NSUserDefaults standardUserDefaults] setObject:model.MobileNumber forKey:@"MobileNumber"];
    [[NSUserDefaults standardUserDefaults] setObject:model.Sex forKey:@"sex"];
    [[NSUserDefaults standardUserDefaults] setObject:model.NickName forKey:@"nickName"];
    [[NSUserDefaults standardUserDefaults] setURL:[NSURL URLWithString:model.UserSoundUrl] forKey:@"SoundUrl"];
    
    [self.navigationController removeFromParentViewController];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window removeAllSubviews];
    window = nil;
    
    [UIApplication sharedApplication].keyWindow.rootViewController = [[HRTabBarViewController alloc] init];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadIconAndBackGroundNotififation" object:nil];
}

- (void)loginEaseMob
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        HRUpdataUserInfoModel *infoModel = [HRUpdataUserInfoModel modelWithJSON:USERINFO];
        EMError *error = [[EMClient sharedClient] loginWithUsername:infoModel.LocalId password:infoModel.Password];
        if (!error){
            DDLog(@"登录聊天服务器成功");
            
            [[EMClient sharedClient].options setIsAutoLogin:YES];
            EMPushOptions *options = [[EMClient sharedClient] pushOptions];
            options.displayStyle = EMPushDisplayStyleMessageSummary;
            options.nickname = infoModel.NickName;
            [[EMClient sharedClient] updatePushOptionsToServer];
        }
        
        
    });
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    [self.view addSubview:self.rootView];
    

    
    if (self.controlType == RegisterVC)
    {
        self.title  = @"注册";
    }else if (self.controlType == ForgetPasswordVC){
        self.title  = @"忘记密码";
    }else if (self.controlType == BindingMobileNumberVC){
        self.title  = @"绑定手机号";
    }
    UIButton *leftButton = [UIButton buttonWithType:0];
    leftButton.frame = CGRectMake(20, kStatusBarHeight, 20, 20);
    [leftButton setImage:[UIImage imageNamed:@"Back-Arrow"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:leftButton aboveSubview:self.view];
    
    
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = self.title;
    titleLabel.font = CustomUIFont(17);
    titleLabel.textColor = [UIColor whiteColor];
    [self.view  addSubview:titleLabel];
    titleLabel.frame = CGRectMake(50, kStatusBarHeight, kFullWidth-100, 30);
    titleLabel.textAlignment = 1;
    
    [self getConfig];

    
}
- (void)clickBack{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:NO];
}

- (void)getConfig{
    YTKApi *api = [YTKApi apiGetWithUrl:@"App/Get_GetSoundCardConfig" para:nil];
    [api getSuccessToken:^() {
        api.foceNoTocken = NO;
        [api setRequestSerializerType:YTKRequestSerializerTypeJSON];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            
            NSDictionary *dict = request.responseJSONObject;
            //            NSLog(@"拿到数据==============%@",[self getCurrentTime]);
            NSDictionary *bodyContentDict = [dict[@"BodyContent"] jsonValueDecoded];
            [[NSUserDefaults standardUserDefaults] setObject:bodyContentDict[@"GuidingText"] forKey:@"GuidingText"];
            [[NSUserDefaults standardUserDefaults] setObject:bodyContentDict[@"SampleText"] forKey:@"SampleText"];
            [[NSUserDefaults standardUserDefaults] setObject:bodyContentDict[@"TipText"] forKey:@"TipText"];
            [[NSUserDefaults standardUserDefaults] setObject:bodyContentDict[@"TextBoxTipText"] forKey:@"TextBoxTipText"];
            [[NSUserDefaults standardUserDefaults] setObject:bodyContentDict[@"TipTitleText"] forKey:@"TipTitleText"];
            [[NSUserDefaults standardUserDefaults] setObject:bodyContentDict[@"manTagList"] forKey:@"manTagList"];
            [[NSUserDefaults standardUserDefaults] setObject:bodyContentDict[@"womanTagList"] forKey:@"womanTagList"];

            
            
            DDLog(@"");
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        }];
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
